package com.hwadee.property.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hwadee.property.mapper.ChargeItemMapper;
import com.hwadee.property.pojo.ChargeItem;
import com.hwadee.property.service.IChargeItemService;
import com.hwadee.property.dto.PageResult;
import com.hwadee.property.util.DateUtil;
import com.hwadee.property.util.ErrorCodes;
import com.hwadee.property.util.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class ChargeItemServiceImpl extends ServiceImpl<ChargeItemMapper, ChargeItem> implements IChargeItemService {

    @Autowired
    private ChargeItemMapper chargeItemMapper;

    @Override
    public PageResult<ChargeItem> getPage(int current, int size, String chargeName, Long communityId, Double amount) {
        // 确保 current 至少为 1
        current = Math.max(current, 1);
        size = Math.max(size, 1);

        // 计算偏移量
        int offset = (current - 1) * size;

        // 查询总记录数
        int total = chargeItemMapper.countChargeItems(chargeName, communityId, amount);

        // 只有当 total > 0 时才查询数据
        List<ChargeItem> records = (total > 0) ? chargeItemMapper.getChargeItems(chargeName, communityId, amount, size, offset) : Collections.emptyList();

        // 返回封装的分页结果
        return new PageResult<>(total, current, size, records);
    }

    @Override
    public List<ChargeItem> listByCommunityId(Long communityId) {
        // 校验社区ID合法性
        if (communityId == null || communityId <= 0) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "小区ID无效");
        }

        // 使用 LambdaQueryWrapper 构造查询条件
        LambdaQueryWrapper<ChargeItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChargeItem::getCommunityId, communityId);
        return this.list(queryWrapper);
    }

    @Override
    public boolean addChargeItem(ChargeItem chargeItem) {
        // 校验 chargeItem 的合法性
        if (chargeItem == null) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "缴费项不能为空");
        }

        // 校验缴费项名称是否已存在
        ChargeItem existing = this.getByChargeName(chargeItem.getChargeName(), chargeItem.getCommunityId());
        if (existing != null) {
            throw new BusinessException(ErrorCodes.ALREADY_EXISTS, "该小区中已有相同的缴费项");
        }

        // 设置创建时间和更新时间
        chargeItem.setCreateTime(DateUtil.dateToString(new Date()));
        chargeItem.setUpdateTime(DateUtil.dateToString(new Date()));
        return this.save(chargeItem);
    }

    @Override
    public boolean updateChargeItem(ChargeItem chargeItem) {
        // 校验 chargeItem 的合法性
        if (chargeItem == null || chargeItem.getId() == null) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "更新的缴费项不能为空或缺少ID");
        }

        // 校验要更新的缴费项是否存在
        ChargeItem existing = this.getById(chargeItem.getId());
        if (existing == null) {
            throw new BusinessException(ErrorCodes.NOT_FOUND, "缴费项未找到");
        }

        // 设置更新时间
        chargeItem.setUpdateTime(DateUtil.dateToString(new Date()));
        return this.updateById(chargeItem);
    }

    @Override
    public boolean deleteChargeItem(Long id) {
        // 校验 id 是否有效
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "删除的缴费项ID无效");
        }

        // 校验要删除的缴费项是否存在
        ChargeItem existing = this.getById(id);
        if (existing == null) {
            throw new BusinessException(ErrorCodes.NOT_FOUND, "缴费项未找到");
        }

        return this.removeById(id);
    }

    @Override
    public ChargeItem getUnitFeeByCommunityID(Long communityID, String feeType) {
        // 校验小区ID
        if (communityID == null) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "小区ID不能为空");
        }
        return this.list(new LambdaQueryWrapper<ChargeItem>()
                .eq(ChargeItem::getCommunityId, communityID)
                .eq(ChargeItem::getChargeName, feeType)).get(0);
    }

    // 辅助方法：根据缴费项名称和小区ID查询是否已存在相同的缴费项
    private ChargeItem getByChargeName(String chargeName, Long communityId) {
        LambdaQueryWrapper<ChargeItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChargeItem::getChargeName, chargeName)
                .eq(ChargeItem::getCommunityId, communityId);
        return this.getOne(queryWrapper);
    }
}
